<?php

namespace Home\Controller;

use Think\Upload;

class UploadController extends HomeController {

    public function __construct() {
        parent::__construct();
        if (!$this->user_info) {
            return $this->error('请先登录');
        }
    }

    public function uploadPhoto($file) {
        $upload = new Upload();// 实例化上传类
        $upload->maxSize = 2097152;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Upload/'; // 设置附件上传根目录
        $upload->savePath = 'home/'; // 设置附件上传（子）目录
        $upload->mimes = array('image/jpeg', 'image/png', 'image/gif');

        $image = $upload->uploadOne($file);
        if ($image !== false) {
            $url = substr($upload->rootPath, 1) . $image['savepath'] . $image['savename'];
            return ['status' => 'success', 'url' => $url];
        } else {
            return ['status' => 'error', 'message' => $upload->getError()];
        }
    }

    /**
     * 上传头像
     * @return string
     */
    public function upload_avatar() {
        if (!$this->user_info) {
            return $this->error('没有权限操作');
        }
        $config = [
            'mimes' => ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'], //允许上传的文件MiMe类型
            'maxSize' => 2097152, //上传的文件大小限制 (0-不做限制)
            'exts' => ['jpg', 'gif', 'png', 'jpeg'], //允许上传的文件后缀
            'savePath' => 'avatar/'
        ];
        $upload = new Upload($config);

        $file = $_FILES['thumb'];
        if (empty($file) || $file['error'] != 0) {
            return '';
        }

        $image = $upload->uploadOne($file);
        if ($image !== false) {
            $url = substr($upload->rootPath, 1) . $image['savepath'] . $image['savename'];
            if (!empty($this->user_info['avatar'])) {
                $file = getcwd() . $this->user_info['avatar'];
                if (file_exists($file)) {
                    unlink($file);
                }
            }
            M('User')->where(['id' => $this->user_info['id']])->save(['avatar' => $url]);
            return $this->success(['url' => $url], '头像更新成功');
        }
        return $this->error('头像更新失败' . $upload->getError());
    }
}